package cn.jasonone.tio.tcp.config;

import cn.hutool.core.util.ReflectUtil;
import cn.jasonone.tio.tcp.TioMessage;
import cn.jasonone.tio.tcp.client.TcpClient;
import cn.jasonone.tio.tcp.config.properties.ClientProperties;
import cn.jasonone.tio.tcp.config.properties.ReconnProperties;
import cn.jasonone.tio.tcp.handler.DataAioHandler;
import cn.jasonone.tio.tcp.listener.AioListenerAdapter;
import cn.jasonone.tio.tcp.listener.GlobalAioListener;
import cn.jasonone.tio.tcp.listener.GlobalIpStatListener;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.tio.client.ClientChannelContext;
import org.tio.client.ClientTioConfig;
import org.tio.client.ReconnConf;
import org.tio.client.TioClient;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.ChannelContext;
import org.tio.core.Node;
import org.tio.core.intf.AioListener;
import org.tio.core.intf.Packet;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Field;

/**
 * @author xujie
 * @version 1.0
 * @date 2022/1/18 8:55
 */
@Slf4j
@Import({TioConfig.class})
public class ClientConfig {
    @Bean
    @ConditionalOnProperty(prefix = "tio.client.reconn", name = "enable", havingValue = "true")
    public ReconnConf reconnConf(ReconnProperties reconnProperties) {
        ReconnConf reconnConf = new ReconnConf();
        reconnConf.setInterval(reconnProperties.getInterval());
        reconnConf.setRetryCount(reconnProperties.getRetryCount());
        return reconnConf;
    }

    @Bean
    public ClientTioConfig tioConfig(DataAioHandler aioHandler, GlobalAioListener aioListener, @Autowired(required = false) ReconnConf reconnConf, GlobalIpStatListener ipStatListener,ClientProperties clientProperties) {
        ClientTioConfig clientTioConfig = new ClientTioConfig(aioHandler, aioListener, reconnConf);
        clientTioConfig.setIpStatListener(ipStatListener);
        clientTioConfig.setHeartbeatTimeout(clientProperties.getHeartbeatTimeout());
        Field field = ReflectUtil.getField(TioMessage.class, "tioConfig");
        ReflectUtil.setFieldValue(null, field, clientTioConfig);
        return clientTioConfig;
    }

    @Bean
    public TioClient tioClient(ClientTioConfig tioConfig) throws IOException {
        return new TioClient(tioConfig);
    }

    @Bean
    public TcpClient tcpClient(TioClient tioClient,ClientProperties clientProperties) {
        return new TcpClient(tioClient,clientProperties);
    }
}
